package com.zkyc.framework.website.strategy;

import com.zkyc.framework.common.constant.NumberConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component("strategyHandler")
@Slf4j
public class StrategyHandler implements InitializingBean, ApplicationContextAware {

    private static final Map<Integer, StrategyService> strategyServiceMap = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() {
        Map<String, StrategyService> beansOfType = applicationContext.getBeansOfType(StrategyService.class);
        beansOfType.forEach((key, value) -> {
            strategyServiceMap.put(value.fetchKey(), value);
            log.info("初始化策略模式的键值对 key={}, value={}", key, value);
        });
    }

    @Override
    public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static StrategyService getStrategy(Integer key) {
        if (null == strategyServiceMap.get(key)) {
            return strategyServiceMap.get(NumberConstant.NUMBER_0);
        }
        return strategyServiceMap.get(key);
    }
}
